package com.cloud.basic.lambda.usage;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;

public class ConsumerTest {

    private static final Map<Integer, String> map = new HashMap<Integer, String>() {
        {
            put(10, "Tom");
            put(3, "Jerry");
        }
    };

    // 679、687、692、
    private static final Map<Integer, Consumer<String>> QUEUE = new ConcurrentHashMap<>();

    public static void resolve(Integer id, Consumer<String> callback) {
        final Consumer<String> existing = QUEUE.get(id);
        if (callback == null) callback = i -> {};
        if (existing != null && callback != existing) {
            callback = existing.andThen(callback);
        }
        QUEUE.put(id, callback);
    }

    public static void main(String[] args) {
        //调用方法，同时编写对结果的回调：此处仅仅打印而已
        test(3, System.out::println);

//        resolve(1, s -> System.out.println(s.toUpperCase()));
//        resolve(1, s -> System.out.println(s.toLowerCase()));
//        resolve(1, s -> System.out.println(s.substring(0, 2)));
//        QUEUE.get(1).accept("Hello World");
    }

    public static void test(Integer age, Consumer<String> consumer) {
        //业务处理
        System.out.println(age);

        //对处理结果的回调:下面的ifPresent参数也是Consumer接口，所有下面三种写法都可以
        //Optional.ofNullable(map.get(age)).ifPresent(e -> consumer.accept(e));
        //Optional.ofNullable(map.get(age)).ifPresent(consumer::accept);
        Optional.ofNullable(map.get(age)).ifPresent(consumer);
    }
}
